/*
 * Copyright 2013 Rivaldo.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.jety.commons.typechecker;

import java.lang.reflect.Method;
import java.lang.reflect.Modifier;

/**
 *
 * @author Rivaldo
 */
public abstract class AbstractTypeChecker {

    //<editor-fold defaultstate="collapsed" desc="Métodos Abstratos">
    public abstract String getTypeName(Class<?> clazz);

    public abstract boolean checkType(Class<?> clazz) throws IllegalArgumentException;
    //</editor-fold>

    //<editor-fold defaultstate="collapsed" desc="Métodos padrões">

    public boolean checkInterface(Class<?> clazz) throws IllegalArgumentException {

        if (!clazz.isInterface()) {
            throw new IllegalArgumentException("Not an interface : " + clazz);
        }

        boolean valid = true;

        for (Method method : clazz.getDeclaredMethods()) {

            int m = method.getModifiers();
            if (Modifier.isStatic(m)) {
                continue;
            }

            valid = checkMethod(method);

            if (!valid) {
                throw new IllegalArgumentException("Invalid method : " + method);
            }
        }

        return valid;
    }

    public boolean checkMethod(Method method) throws IllegalArgumentException {
        return checkReturnType(method) && checkParametersType(method);
    }

    //</editor-fold>

    //<editor-fold defaultstate="collapsed" desc="Métodos auxiliares">

    protected boolean checkParametersType(Method method) throws IllegalArgumentException {

        boolean valid = true;

        for (Class<?> paramType : method.getParameterTypes()) {

            valid = checkType(paramType);

            if (!valid) {
                throw new IllegalArgumentException("Invalid parameter type : " + paramType);
            }
        }

        return valid;
    }

    protected boolean checkReturnType(Method method) throws IllegalArgumentException {

        Class<?> returnType = method.getReturnType();
        boolean valid = checkType(returnType);


        if (!valid) {
            throw new IllegalArgumentException("Invalid return type : " + returnType);
        }

        return true;
    }

    //</editor-fold>

}

